import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {

    // 根据用户账号查询用户
    public User findByUserAccount(String userAccount) {
        String query = "SELECT * FROM user WHERE user_account = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            pstmt = conn.prepareStatement(query);
            pstmt.setString(1, userAccount);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserAccount(rs.getString("user_account"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.closeResources(conn, pstmt, rs);
        }
        return null;
    }

    // 添加新用户
    public boolean addUser(User user) {
        String sql = "INSERT INTO user (username, user_account, password) VALUES (?, ?, ?)";
        int flag = JdbcUtils.executeUpdate(
                sql,
                user.getUsername(),
                user.getUserAccount(),
                user.getPassword()
        );
        return flag > 0;
    }

    // 可选：获取所有用户（根据你的需求）
    public List<User> findAll() {
        List<User> userList = new ArrayList<>();
        String query = "SELECT * FROM user";

        try {
            ResultSet rs = JdbcUtils.executeQuery(query);
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setUserAccount(rs.getString("user_account"));
                user.setPassword(rs.getString("password"));
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;
    }
}